//
//  BIDAddCommonRepairViewController.m
//  HJGJCommunity
//
//  Created by mal on 2017/6/2.
//  Copyright © 2017年 mal. All rights reserved.
//

#import "BIDAddCommonRepairViewController.h"
#import "BIDBrowserImageViewController.h"
#import "BIDAddPhotoView.h"
#import "BIDCustomTextView.h"
#import "BIDUploadFile.h"

#import <MobileCoreServices/UTCoreTypes.h>

static NSString *submitRepairURL = @"client/repair/addPublicRepair.action";

@interface BIDAddCommonRepairViewController ()<BIDAddPhotoViewDelegate, ELCImagePickerControllerDelegate, UINavigationControllerDelegate, BIDUploadFileDelegate>
{
    NSArray *_chosenImgArr;
    BIDUploadFile *_uploadFile;
}

@end

@implementation BIDAddCommonRepairViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"公共报修";
    _textView.layer.borderColor = RGBACOLOR(193.f, 193.f, 193.f, 1.f).CGColor;
    _textView.layer.borderWidth = 1.f;
    _textView.placeholder = @"请填写报修内容...";
    _textView.inputAccessoryView = self.toolBar;
    //
    _addPhotoView.delegate = self;
    //
    _chosenImgArr = [[NSArray alloc] init];
    //
    _uploadFile = [[BIDUploadFile alloc] initWithURL:[[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getPayServerAddr], submitRepairURL]];
    _uploadFile.delegate = self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 提交报修

 @param sender <#sender description#>
 */
- (IBAction)submitRepair:(id)sender
{
    NSString *strContent = _textView.text;
    if(strContent.length == 0)
    {
        [self showAlertView:@"报修内容不能为空" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        return;
    }
    if(_chosenImgArr.count > 0)
    {
        [_uploadFile addData:@"repairWeb.userId" value:[AppDelegate getUserId]];
        [_uploadFile addData:@"repairWeb.content" value:strContent];
        int count = 1;
        for(UIImage *img in _chosenImgArr)
        {
            NSString *strFileName = [[NSString alloc] initWithFormat:@"fileName%d", count];
            NSData *imgData = UIImageJPEGRepresentation(img, 0.5f);
            [_uploadFile addFileFromMemory:strFileName fieldName:@"uploadFile" data:imgData];
            [_uploadFile addData:@"uploadFileFileName" value:strFileName];
            count++;
        }
        [_uploadFile finishAddFile];
        [_uploadFile startUpload];
    }
    else
    {
        NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getPayServerAddr], submitRepairURL];
        NSString *strPost = [[NSString alloc] initWithFormat:@"repairWeb.userId=%@&repairWeb.content=%@", [AppDelegate getUserId], strContent];
        [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
            if(errMsg)
            {
                [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
            }
            else
            {
                [self showAlertView:@"提交成功" buttonTitle:ALERT_BTN_TITLE tag:@100 functionName:@"alertViewHandler"];
            }
        }];
    }
}

- (void)alertViewHandler
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - BIDUploadFileDelegate
- (void)finishUploadWithResult:(id)obj
{
    if([obj isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *dic = (NSDictionary *)obj;
        dic = dic[@"head"];
        NSNumber *value = dic[@"success"];
        if([value intValue] == 1)
        {
            [self showAlertView:@"提交成功" buttonTitle:ALERT_BTN_TITLE tag:@100 functionName:@"alertViewHandler"];
        }
        else
        {
            [self showAlertView:@"提交失败" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
    }
}

- (void)uploadFailedWithError:(NSError *)err
{
    [self showAlertView:[err localizedDescription] buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
}

#pragma mark - BIDAddPhotoViewDelegate
- (void)choosePhoto
{
    if(_addPhotoView.imgArr.count == 3)
    {
        [self showAlertView:@"最多选择3张图片" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        return;
    }
    //
    ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initImagePicker];
    
    //
    elcPicker.maximumImagesCount = 3-_addPhotoView.imgArr.count; //Set the maximum number of images to select to 100
    elcPicker.returnsOriginalImage = YES; //Only return the fullScreenImage, not the fullResolutionImage
    elcPicker.returnsImage = YES; //Return UIimage if YES. If NO, only return asset location information
    elcPicker.onOrder = YES; //For multiple image selection, display and return order of selected images
    elcPicker.mediaTypes = @[(NSString *)kUTTypeImage]; //Supports image and movie types((NSString *)kUTTypeMovie)
    
    elcPicker.imagePickerDelegate = self;
    
    [self presentViewController:elcPicker animated:YES completion:nil];
}

- (void)resizeViewWithFrame:(CGRect)frame
{
    _heightForPhotoViewConstraint.constant = CGRectGetHeight(frame);
    [self.view layoutIfNeeded];
}

- (void)showPhotoAtIndex:(NSInteger)index withImgArr:(NSArray *)arr
{
    BIDBrowserImageViewController *vc = [[BIDBrowserImageViewController alloc] initWithNibName:@"BIDBrowserImageViewController" bundle:nil];
    vc.imgArr = arr;
    vc.index = index;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - ELCImagePickerControllerDelegate Methods

- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:[info count]];
    for (NSDictionary *dict in info)
    {
        if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto)
        {
            if ([dict objectForKey:UIImagePickerControllerOriginalImage])
            {
                UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
                [images addObject:image];
                [_addPhotoView addPhoto:image];
            }
            else
            {
                NSLog(@"UIImagePickerControllerReferenceURL = %@", dict);
            }
        }
        else if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypeVideo)
        {
            if ([dict objectForKey:UIImagePickerControllerOriginalImage])
            {
                UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
                [images addObject:image];
            }
            else
            {
                NSLog(@"UIImagePickerControllerReferenceURL = %@", dict);
            }
        }
        else
        {
            NSLog(@"Uknown asset type");
        }
    }
    _chosenImgArr = images;
}

- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
